#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import db_conf
import cgi
import os
import smtplib

def sendMail(pname, receivers, jobid, url):
    initials = pname.split("@")[0]
    sender = 'jake.lin@uni.lu'
    receivers.append("christian.jaeger@uni.lu")
    message = """From: Metabolomics GCMS <christian.jaeger@uni.lu>
To: GCMS User
Subject: %s

%s
    """ %(jobid + "_" + initials, "Hello " + pname + ",\n\nGCMSJob results are posted. Use link below to access result files and cost summary.\n" + url + "\n\nCheers and feel free to contact Christian/Jake with questions")

    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message)
    except SMTPException:
        print "Error: unable to send email"

def post_results(cur, gcmsjobid, operator, results_date, machinehours, machinerate, addcost, costnotes, costtotal, rawf, statf, additionalf, filenotes, methodnotes, machine):
    try:
        cur.execute("""insert into gcms_job_results (gcmsjobid, operator, results_date, machinehours, machinerate, addcost, costnotes, costtotal, rawf, statf, additionalf, filenotes, methodnotes, machine) values (%s, %s, %s, %s, %s, %s, %s, %s, %s,%s, %s, %s, %s, %s) RETURNING resultskey""", ( gcmsjobid, operator, results_date, machinehours, machinerate, addcost, costnotes, costtotal, rawf, statf, additionalf, filenotes, methodnotes, machine))
        return cur.fetchone()[0]
    except psycopg2.DatabaseError, e:         
        print 'Adding/updating new experiment error %s' % e
        return -1

def post_gc_status(cur, jobkey, status):
    try:
        cur.execute("update gcms_sample_job set gcstatus = '" + status + "' where id = " + jobkey )
    except psycopg2.DatabaseError, e:
        print 'Updating status error %s' % e

con = None

try:
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    qform = cgi.FieldStorage()
    jobid = qform.getvalue('jobkey')
    contactemail = qform.getvalue('contactemail')
    operator = qform.getvalue('operator')
    results_date = qform.getvalue('results_date')
    machinehours = qform.getvalue('machinehours')
    machinerate = qform.getvalue('machinerate')
    addcost = qform.getvalue('addcost')
    costnotes = qform.getvalue('costnotes')
    costtotal = qform.getvalue('costtotal')
    personname = qform.getvalue('pname')
    methodnotes = qform.getvalue('methodnotes')
    filenotes = qform.getvalue('filenotes')
    external = qform.getvalue("_source")
    machine = qform.getvalue('gcmachine')
    cur = con.cursor()
    rawfile = qform['rawf']
    statfile = qform['statf']
    addfile = qform['additionalf']
    rawfn = ""
    statfn = ""
    additionalfn = ""
    if (external == None):
        external = ""
    if (not os.path.exists('/var/www/gcmsjob' + external + '/results/' + jobid)):
        os.system("mkdir /var/www/gcmsjob" + external + "/results/" + jobid)
    if rawfile.filename:
        # strip leading path from file name to avoid 
        # directory traversal attacks
        fn = os.path.basename(rawfile.filename)
	rawfn = fn
        open('/var/www/gcmsjob' + external + '/results/' + jobid + '/' + fn, 'w').write(rawfile.file.read())
    if statfile.filename:
        fn = os.path.basename(statfile.filename)
	statfn = fn
        open('/var/www/gcmsjob' + external + '/results/' + jobid + '/' + fn, 'w').write(statfile.file.read())
    if addfile.filename:
        fn = os.path.basename(addfile.filename)
	additionalfn = fn
        open('/var/www/gcmsjob' + external + '/results/' + jobid + '/' + fn, 'w').write(addfile.file.read())
    #os.system("touch /var/www/gcmsjob/results/abc.dat")
    resultskey = post_results(cur, jobid, operator, results_date, machinehours, machinerate, addcost, costnotes, costtotal, rawfn, statfn, additionalfn, filenotes, methodnotes, machine)
    post_gc_status(cur, jobid, "Completed")
    pa = {}	
    print "Content-type: text/html;charset=utf-8\r\n"
    cur.execute("commit")
    pa['_status'] = "200"
    pa['resultskey'] = resultskey
    if (operator != "jlin212@gmail.com"):
        sendMail(personname, ["jlin212@gmail.com", contactemail], "Completed results: " + str(jobid), "http://metabolomics.uni.lux/gcms_platform/index.html?jobkey=" + "_" + str(jobid))
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    
    if con:
        con.close()
